/**
 * Copyright Shper.cn Corporation 2012
 */
package cn.shper.srename;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.events.VerifyListener;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TableItem;

/**
 * @Description: TODO
 * @Version: 0.1 2012-11-24
 * @Author: Shper
 * @Since: JDK 7.0
 */
public class SReName extends Shell {

    private DPanel dPanel;
    private List<File> fileList;

    /**
     * Main
     * @param args
     */
    public static void main(String args[]) {
        try {
            Display display = Display.getDefault();
            SReName shell = new SReName(display);
            shell.open();
            shell.layout();
            while (!shell.isDisposed()) {
                if (!display.readAndDispatch()) {
                    display.sleep();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Create the shell.
     * 
     * @param display
     */
    public SReName(Display display) {
        super(display, SWT.CLOSE | SWT.MIN | SWT.TITLE);
        setText("SReName V1.0");
        setLayout(null);
        setSize(660, 580);
        dPanel = new DPanel(this, SWT.NONE);
        createListenners();
    }

    private void createListenners() {
        // 源地址 选择 按钮按下
        dPanel.getSrcBtn().addMouseListener(new SrcBtnAction());
        // 源地址Txt值变更事件
        dPanel.getSrcPathTxt().addModifyListener(new SrcPathTxtChangeAction());
        // 命名规则Txt值变更事件
        dPanel.getReNameTxt().addModifyListener(new ReNameTxtChangeAction());
        // 步长Txt值变更事件
        dPanel.getStepTxt().addModifyListener(new ReNameTxtChangeAction());
        dPanel.getStepTxt().addVerifyListener(new StepTxtVerifyAction());
        // 输出地址 值变更事件
        dPanel.getOutPathTxt().addModifyListener(new OutPathTxtChangeAction());
        // 输出地址 按钮按下
        dPanel.getOutBtn().addMouseListener(new OutBtnAction());
        // 确定 按钮按下
        dPanel.getOkBTN().addSelectionListener(new OkBtnAction());
    }

    /*
     * 源地址 选择 按钮按下
     */
    class SrcBtnAction extends MouseAdapter {
        public void mouseDown(MouseEvent e) {
            DirectoryDialog dDialog = new DirectoryDialog(getShell());
            dDialog.open();
            if (!isEmpty(dDialog.getFilterPath())) {
                dPanel.getSrcPathTxt().setText(dDialog.getFilterPath());
            }
        }
    }

    /*
     * 输出地址 按钮按下
     */
    class OutBtnAction extends MouseAdapter {
        public void mouseDown(MouseEvent e) {
            DirectoryDialog dDialog = new DirectoryDialog(getShell());
            dDialog.open();
            if (!isEmpty(dDialog.getFilterPath())) {
                dPanel.getOutPathTxt().setText(dDialog.getFilterPath());
            }
        }
    }

    /*
     * 源地址Txt值变更事件
     */
    class SrcPathTxtChangeAction implements ModifyListener {
        public void modifyText(ModifyEvent e) {
            // OK按钮 控制
            okBtnControl();
            dPanel.getFileTbl().removeAll();
            File srcfile = new File(dPanel.getSrcPathTxt().getText());
            File[] srcFiles = srcfile.listFiles();
            if (null != srcFiles) {
                fileList = new ArrayList<File>();
                for (File file : srcFiles) {
                    if (!file.isDirectory()) {
                        TableItem item = new TableItem(dPanel.getFileTbl(), SWT.None);
                        item.setText(0, String.valueOf(dPanel.getFileTbl().getItemCount()));
                        item.setText(1, file.getName());
                        fileList.add(file);
                    }
                }
            }
            dPanel.getReNameTxt().setText("");
            dPanel.getStepTxt().setText("");
        }
    }

    class StepTxtVerifyAction implements VerifyListener {
        public void verifyText(VerifyEvent e) {
            // 几种情况，输入控制键，输入中文，输入字符，输入数字
            // 正整数验证
            Pattern pattern = Pattern.compile("[0-9]\\d*");
            Matcher matcher = pattern.matcher(e.text);
            if (matcher.matches()) {
                // 处理数字
                e.doit = true;
            } else if (e.text.length() > 0) {
                // 有字符情况,包含中文、空格
                e.doit = false;
            } else {
                // 控制键
                e.doit = true;
            }
        }
    }
    
    /*
     * 命名规则Txt & 步长Txt值变更事件
     */
    class ReNameTxtChangeAction implements ModifyListener {
        public void modifyText(ModifyEvent e) {
            // OK按钮 控制
            okBtnControl();
            String nameTem = dPanel.getReNameTxt().getText();
            String stepTem = dPanel.getStepTxt().getText();

            for (int i = 0; i < dPanel.getFileTbl().getItemCount(); i++) {
                String oldName = dPanel.getFileTbl().getItem(i).getText(1);
                String exName = subString(oldName, oldName.lastIndexOf("."));
                dPanel.getFileTbl().getItem(i).setText(2, nameTem + stepAppend(stepTem, i) + exName);
            }
        }
    }
    
    class OutPathTxtChangeAction implements ModifyListener{
        public void modifyText(ModifyEvent e) {
            // OK按钮 控制
            okBtnControl();
        }
    }

    /*
     * 确定 按钮按下
     */
    class OkBtnAction extends SelectionAdapter {
        public void widgetSelected(SelectionEvent e) {
            String outPath = dPanel.getOutPathTxt().getText();
            if (!isEmpty(outPath)) {
                File outFile = new File(outPath);
                if (!outFile.exists()) {
                    outFile.mkdirs();
                } else if (!outFile.isDirectory()) {
                    return;
                }
                for (int i = 0; i < fileList.size(); i++) {
                    String newName = dPanel.getFileTbl().getItem(i).getText(2);
                    copyFile(fileList.get(i), outPath + "\\" + newName);
                }
                MessageBox msgBox = new MessageBox(getShell(), SWT.OK | SWT.ICON_INFORMATION);
                msgBox.setText("通知");
                msgBox.setMessage("重命名完成");
                msgBox.open();
            }
        }
    }

    /*
     * 文件拷贝
     */
    private void copyFile(File file, String outFilePath) {
        BufferedInputStream inBuffer = null;
        BufferedOutputStream outBuffer = null;

        try {
            inBuffer = new BufferedInputStream(new FileInputStream(file));
            outBuffer = new BufferedOutputStream(new FileOutputStream(outFilePath));

            // 缓冲数组
            byte[] b = new byte[1024 * 5];
            int len;
            while ((len = inBuffer.read(b)) != -1) {
                outBuffer.write(b, 0, len);
            }
            // 刷新此缓冲的输出流
            outBuffer.flush();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            // 关闭流
            try {
                if (null != inBuffer) {
                    inBuffer.close();
                }
                if (null != outBuffer) {
                    outBuffer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    // OK按钮 控制
    private void okBtnControl() {
        if (dPanel.getFileTbl().getItemCount() > 0 && !isEmpty(dPanel.getReNameTxt().getText())
                && !isEmpty(dPanel.getStepTxt().getText()) && !isEmpty(dPanel.getOutPathTxt().getText())) {
            dPanel.getOkBTN().setEnabled(true);
        } else {
            dPanel.getOkBTN().setEnabled(false);            
        }
    }

    // 字符串空值检测
    private boolean isEmpty(String str) {
        if (null == str || 0 == str.length()) {
            return true;
        }
        return false;
    }

    // 字符串截取
    private String subString(String str, int index) {
        if (!isEmpty(str) && index > 0) {
            str = str.substring(index);
        }
        return str;
    }
    
    // 步长运算
    private String stepAppend(String stepTem, int i) {
        StringBuffer sb = new StringBuffer("");
        if (!isEmpty(stepTem)) {
            String step = String.valueOf(Integer.parseInt(stepTem) + i);
            sb = new StringBuffer(step);
            while (stepTem.length() > sb.length()) {
                sb.insert(0, "0");
            }
        }
        return sb.toString();
    }

    protected void checkSubclass() {
    }
}
